import React, { useState, useRef } from 'react';
import { Button, Input, Table, Form, Space, Pagination, Modal, message } from 'antd';
import { PlusOutlined, DeleteOutlined, ArrowLeftOutlined } from '@ant-design/icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { Descriptions, Form as AntdForm, InputNumber } from 'antd';

const mockData = [
  { key: 1, name: '冬青楼', code: 'A1', floors: 15, fee: 2.1, area: 5400, managed: 4100, order: 1 },
  { key: 2, name: '四季春', code: 'A2', floors: 12, fee: 2.1, area: 5200, managed: 4300, order: 2 },
  { key: 3, name: '月桂苑', code: 'A3', floors: 21, fee: 2.1, area: 6700, managed: 5700, order: 3 },
  { key: 4, name: '牡丹亭', code: 'B1', floors: 21, fee: 2.1, area: 6700, managed: 6100, order: 4 },
  { key: 5, name: '洛阳城', code: 'B2', floors: 12, fee: 2.1, area: 6200, managed: 5100, order: 5 },
  { key: 6, name: '风维林', code: 'B3', floors: 4, fee: 3, area: 3000, managed: 2100, order: 6 },
  { key: 7, name: '虎丘城', code: 'C1', floors: 4, fee: 3, area: 4200, managed: 3100, order: 7 },
  { key: 8, name: '涟漪沙', code: 'C2', floors: 12, fee: 2.1, area: 5600, managed: 5400, order: 8 },
  { key: 9, name: '风雅致', code: 'C3', floors: 7, fee: 2.6, area: 7640, managed: 7200, order: 9 },
  { key: 10, name: '梵楼', code: 'D1', floors: 4, fee: 3, area: 3100, managed: 3100, order: 10 },
];

export default function BuildingManage() {
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [data, setData] = useState(mockData);
  const allDataRef = useRef(mockData); // 保存所有数据
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const location = useLocation();

  // 空间管理弹窗状态
  const [spaceVisible, setSpaceVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [editMode, setEditMode] = useState(false);
  const [editValues, setEditValues] = useState({});

  // 接收新数据
  React.useEffect(() => {
    if (location.state && location.state.newBuilding) {
      setData(prevData => [location.state.newBuilding, ...prevData]);
      allDataRef.current = [location.state.newBuilding, ...allDataRef.current];
    }
    // eslint-disable-next-line
  }, [location.state]);

  // 查询功能
  const handleSearch = async () => {
    const values = await form.getFieldsValue();
    const name = values.name?.trim();
    if (!name) {
      setData(allDataRef.current);
      return;
    }
    setData(allDataRef.current.filter(item => item.name.includes(name)));
  };

  // 重置功能
  const handleReset = () => {
    form.resetFields();
    setData(allDataRef.current);
  };

  const columns = [
    { title: '楼宇名称', dataIndex: 'name', align: 'center' },
    { title: '楼宇编号', dataIndex: 'code', align: 'center' },
    { title: '层数', dataIndex: 'floors', align: 'center' },
    { title: '物业费（元/平/月）', dataIndex: 'fee', align: 'center' },
    { title: '建筑面积（㎡）', dataIndex: 'area', align: 'center' },
    { title: '在管面积', dataIndex: 'managed', align: 'center' },
    { title: '排序', dataIndex: 'order', align: 'center' },
    {
      title: '操作',
      align: 'center',
      render: (_, record) => (
        <Space>
          <Button type="link" onClick={() => { setCurrentRecord(record); setSpaceVisible(true); }}>空间管理</Button>
          <Button type="link" danger onClick={() => handleDelete(record.key)}>删除</Button>
        </Space>
      ),
    },
  ];

  const handleDelete = (key) => {
    Modal.confirm({
      title: '确认删除该楼宇吗？',
      onOk: () => setData(data.filter(item => item.key !== key)),
    });
  };

  const handleBatchDelete = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择要删除的楼宇');
      return;
    }
    Modal.confirm({
      title: '确认批量删除所选楼宇吗？',
      onOk: () => {
        setData(data.filter(item => !selectedRowKeys.includes(item.key)));
        setSelectedRowKeys([]);
      },
    });
  };

  return (
    <div style={{ background: '#fff', minHeight: '100vh', padding: 24 }}>
      <div style={{ display: 'flex', alignItems: 'center', marginBottom: 24 }}>
        <Button type="default" icon={<ArrowLeftOutlined />} onClick={() => navigate('/dashboard/enterprise')} style={{ marginRight: 16 }}>
          返回
        </Button>
        <div style={{ fontWeight: 700, fontSize: 24, borderLeft: '6px solid #4880ff', paddingLeft: 12 }}>
          楼宇信息管理
        </div>
      </div>
      <div style={{ background: '#fff', borderRadius: 8, border: '1px solid #e5e6eb', padding: 24, marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: 16 }}>
          <Button type="primary" icon={<PlusOutlined />} style={{ marginRight: 16 }} onClick={() => navigate('/building/create')}>新增</Button>
          <Button style={{ background: '#ffc107', color: '#fff', border: 'none' }} icon={<DeleteOutlined />} onClick={handleBatchDelete}>批量删除</Button>
        </div>
        <Form layout="inline" form={form} style={{ marginBottom: 16 }}>
          <Form.Item label="楼宇名称:" name="name">
            <Input placeholder="请输入楼宇名称" style={{ width: 300 }} />
          </Form.Item>
          <Button type="primary" style={{ marginLeft: 16 }} onClick={handleSearch}>查询</Button>
          <Button style={{ marginLeft: 16 }} onClick={handleReset}>重置</Button>
        </Form>
        <Table
          rowSelection={{
            selectedRowKeys,
            onChange: setSelectedRowKeys,
          }}
          columns={columns}
          dataSource={data}
          pagination={false}
          bordered
          style={{ background: '#fff' }}
        />
        {/* 空间管理弹窗 */}
        <Modal
          open={spaceVisible}
          title="空间管理"
          footer={null}
          onCancel={() => { setSpaceVisible(false); setEditMode(false); }}
          width={500}
        >
          {currentRecord && !editMode && (
            <>
              <Descriptions column={1} bordered size="middle">
                <Descriptions.Item label="楼宇名称">{currentRecord.name}</Descriptions.Item>
                <Descriptions.Item label="楼宇编号">{currentRecord.code}</Descriptions.Item>
                <Descriptions.Item label="层数">{currentRecord.floors}</Descriptions.Item>
                <Descriptions.Item label="物业费">{currentRecord.fee} 元/平/月</Descriptions.Item>
                <Descriptions.Item label="建筑面积">{currentRecord.area} ㎡</Descriptions.Item>
                <Descriptions.Item label="在管面积">{currentRecord.managed} ㎡</Descriptions.Item>
                <Descriptions.Item label="排序">{currentRecord.order}</Descriptions.Item>
              </Descriptions>
              <div style={{textAlign: 'right', marginTop: 16}}>
                <Button type="primary" onClick={() => { setEditMode(true); setEditValues(currentRecord); }}>修改</Button>
              </div>
            </>
          )}
          {currentRecord && editMode && (
            <AntdForm
              layout="vertical"
              initialValues={editValues}
              onFinish={values => {
                setData(data.map(item => item.key === currentRecord.key ? { ...item, ...values } : item));
                setCurrentRecord(prev => ({ ...prev, ...values }));
                setEditMode(false);
                message.success('修改成功');
              }}
            >
              <AntdForm.Item label="楼宇名称" name="name" rules={[{ required: true, message: '请输入楼宇名称' }]}> <Input /> </AntdForm.Item>
              <AntdForm.Item label="楼宇编号" name="code" rules={[{ required: true, message: '请输入楼宇编号' }]}> <Input /> </AntdForm.Item>
              <AntdForm.Item label="层数" name="floors" rules={[{ required: true, message: '请输入层数' }]}> <InputNumber min={1} style={{width:'100%'}} /> </AntdForm.Item>
              <AntdForm.Item label="物业费(元/平/月)" name="fee" rules={[{ required: true, message: '请输入物业费' }]}> <InputNumber min={0} step={0.1} style={{width:'100%'}} /> </AntdForm.Item>
              <AntdForm.Item label="建筑面积(㎡)" name="area" rules={[{ required: true, message: '请输入建筑面积' }]}> <InputNumber min={0} style={{width:'100%'}} /> </AntdForm.Item>
              <AntdForm.Item label="在管面积(㎡)" name="managed" rules={[{ required: true, message: '请输入在管面积' }]}> <InputNumber min={0} style={{width:'100%'}} /> </AntdForm.Item>
              <AntdForm.Item label="排序" name="order" rules={[{ required: true, message: '请输入排序' }]}> <InputNumber min={1} style={{width:'100%'}} /> </AntdForm.Item>
              <div style={{textAlign: 'right'}}>
                <Button onClick={() => setEditMode(false)} style={{marginRight: 8}}>取消</Button>
                <Button type="primary" htmlType="submit">保存</Button>
              </div>
            </AntdForm>
          )}
        </Modal>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 24 }}>
          <span>共 100 条</span>
          <Pagination
            total={100}
            showSizeChanger
            showQuickJumper
            pageSizeOptions={[10, 20, 50]}
            defaultPageSize={10}
            style={{ marginRight: 16 }}
          />
          <span>
            到第 <Input style={{ width: 50, margin: '0 8px' }} size="small" /> 页
            <Button size="small">确定</Button>
          </span>
        </div>
      </div>
    </div>
  );
} 